package com.uenpay.im.invokeitems;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.uenpay.im.IMApplication;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * @Author: SL
 * @Date: 2016/11/30 14:54
 * @CopyRight: http://www.qiyunxin.com
 * @Parameter: TODO
 * @Function: TODO
 */
public class HttpPostRequest {

    public static String REQUESTMETHOD_POST = "POST";
    public static String REQUESTMETHOD_DELETE = "DELETE";

    public interface IRequest {
        void onResult(int responseCode, String response);
    }

    /**
     * @param url      请求地址
     * @param jsonData 请求参数
     * @param iRequest 回调
     */
    public static void onRequest(String url, String jsonData, String requestMethod, IRequest iRequest) {
        new RequestAsync(url, jsonData, requestMethod, iRequest).execute();
    }


    private static class RequestAsync extends AsyncTask<Void, Void, Void> {
        private String jsonData;
        private IRequest mIRequest;
        private String requestUrl;
        private String requestMethod;

        public RequestAsync(String _url, String _jsonData, String _requestMethod, IRequest _IRequest) {
            requestMethod = _requestMethod;
            requestUrl = _url;
            jsonData = _jsonData;
            mIRequest = _IRequest;
        }

        @Override
        protected Void doInBackground(Void... params) {
            URL url = null;
            HttpURLConnection conn = null;
            try {

                url = new URL(requestUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                if (requestMethod.equals(REQUESTMETHOD_POST)) {
                    conn.setDoInput(true);// 允许输入
                    conn.setDoOutput(true);// 允许输出
                }
                conn.setUseCaches(false);// 不使用Cache
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("app_id", "qiyunxin");
                conn.setRequestProperty("Authorization", IMApplication.getInstance().getUcrtoken());
                conn.setRequestProperty("_token", IMApplication.getInstance().getAccessToken());
                conn.setRequestProperty("_custid", IMApplication.getCustId());
                conn.setRequestProperty("Content-Length",
                        String.valueOf(jsonData.getBytes().length));
                conn.setRequestProperty("Content-Type", "text/*;charset=utf-8");
                conn.setRequestMethod(requestMethod);
                if (requestMethod.equals(REQUESTMETHOD_POST)) {
                    DataOutputStream outStream = new DataOutputStream(
                            conn.getOutputStream());
                    if (!TextUtils.isEmpty(jsonData)) {
                        outStream.write(jsonData.getBytes());
                    }
                    outStream.flush();
                    outStream.close();
                }
                if (conn == null) {
                    Log.e("conn:", "连接为null");
                    return null;
                }
                int responseCode = conn.getResponseCode();
                Log.e("reponsemsg:", conn.getResponseMessage());
                InputStream input = null;
                if (responseCode == 200) {
                    input = conn.getInputStream();
                } else {
                    input = conn.getErrorStream();
                }
                if (input != null) {
                    byte[] data = readStream(input);
                    mIRequest.onResult(responseCode, new String(data, "UTF-8"));
                } else {
                    mIRequest.onResult(-1, "");
                }
//
//                if (responseCode == 200) {
//                    input = conn.getInputStream();
//                    if (input != null) {
//                        byte[] data = readStream(input);
//                        mIRequest.onResult(responseCode,new String(data, "UTF-8"));
//                    }
//                } else {
//                    Log.e("请求失败：", "-->" + responseCode);
//                    mIRequest.onResult("");
//                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    // 获取连接返回的数据
    private static byte[] readStream(InputStream inputStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        byte[] data = baos.toByteArray();
        inputStream.close();
        baos.close();
        return data;
    }
}
